package middleware

import (
	"sync"

	"github.com/gin-gonic/gin"
)

func HandlerAuthority() gin.HandlerFunc {
	return func(c *gin.Context) {
		if isExclude(c.Request.URL.Path) {
			c.Next()
			return
		}

		c.Next()
	}
}

func NewAuthority(config *AuthorityConfig) error {
	authConfig = config
	return nil
}

// 权限配置
type AuthorityConfig struct {
	HeaderAuthKey string          // 校验key
	Excludes      map[string]bool // 排除鉴权的接口
}

var (
	authConfig *AuthorityConfig
	authMux    sync.Mutex
)

func isExclude(path string) bool {
	authMux.Lock()
	defer authMux.Unlock()

	_, ok := authConfig.Excludes[path]
	if ok {
		return true
	}

	return false
}
